package com.wstuo.common.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Zip tool
 *
 */
public class ZipUtils {
	
	private final static int SIZE = 1024;
	private static int DATALENGTH = 0;
	public static String EXTENSION_ZIP=".zip";
	/**
	 * @param file
	 * @param desFile
	 * @param startTime
	 * @param endTime
	 * @throws IOException
	 */
	public static void zip(File file, String desFile,Date startTime,Date endTime) throws IOException {
		ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(desFile));
		if (file.isDirectory()) {
			File[] files = file.listFiles();
			for (int i = 0 ; i < files.length ; i++ ) {
				Date lasModeified = new Date(files[i].lastModified());
				if(lasModeified.after(startTime) && lasModeified.before(endTime)){
					compress(files[i], zipOutputStream);
				}
			}
		} else {
			compress(file, zipOutputStream);
		}

		if(zipOutputStream != null){
			zipOutputStream.closeEntry(); 
			zipOutputStream.flush();
			zipOutputStream.close();
			zipOutputStream = null;
		}
	}
	
	/**
	 * 文件压缩
	 * 
	 * @param file
	 * @param desDir
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	private static void compress(File file, ZipOutputStream os )
			throws  IOException {
		InputStream in = new BufferedInputStream(new FileInputStream(file));
//		Checksum cksum = new CRC32();// 校验码
//		CheckedOutputStream checkedOutputStream = new CheckedOutputStream(
//				new FileOutputStream(des), cksum);
		ZipEntry zipEntry = new ZipEntry(file.getName());
		os.putNextEntry(zipEntry);
		byte[] b = new byte[SIZE];
		while ((DATALENGTH = in.read(b)) > 0) {
			os.write(b, 0, DATALENGTH);
		}
	}
}
